package initialization

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
	"willow/common/conf"
)

func init()  {
	readWillowConf()
}

/**
 * 读取willow.conf配置文件
 */
func readWillowConf() {
	file,err := os.OpenFile(conf.WillowPath,os.O_RDONLY | os.O_CREATE,0666)
	if err != nil {
		fmt.Println("open file err=",err)
	}

	defer file.Close();

	stringConf := []string{}
	reader := bufio.NewReader(file)							//带缓冲区的读取文件的方式，适合文件比较大的情况
	for  {
		str,err := reader.ReadString('\n')  			//读取到一个换行符结束
		if str != "" && strings.Contains(str,":") && strings.Index(str,"#") != 0{
			stringConf = append(stringConf, str)
		}
		if err != nil || err == io.EOF {					//io.EOF表示文件的末尾
			break
		}
	}
	analysisString(stringConf)
}

func analysisString(stringConf []string)  {
	conf.WillowConf = make(map[string]string)
	var temp  []string
	for i := 0; i < len(stringConf) ; i++  {
		if strings.Contains(stringConf[i],"#") {
			stringConf[i] = strings.Split(stringConf[i],"#")[0]
		}
		temp = strings.Split(stringConf[i],":")
		conf.WillowConf[strings.TrimSpace(temp[0])] = strings.TrimSpace(temp[len(temp)-1])
	}
}


